package dao

import models.Tables._
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import shared.pojo.Role
import slick.jdbc.JdbcProfile

import javax.inject.{Inject, Singleton}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

@Singleton
class WechatMemberDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends
  HasDatabaseConfigProvider[JdbcProfile] {

  import utils.MyPostgresProfile.api._
  import com.github.tototoshi.slick.PostgresJodaSupport._

  type MyRow = WechatMemberRow
  val table = WechatMember

  def insert(row: MyRow) = {
    db.run(table += row)
  }

  def selectAll = db.run(table.sortBy(_.createTime.desc).result.map(_.toList))

  def select(phone: String) = db.run(table.filter(_.phone === phone).
    result.head)

  def selectOp(phone: String) = db.run(table.filter(_.phone === phone).
    result.headOption)

  def phoneExist(account: String) = db.run(table.
    filter(_.phone === account).exists.result)

  def deleteByPhone(phone: String): Future[Unit] = db.run(table.filter(_.phone === phone).delete).map(_ => ())

  def update(row: MyRow): Future[Unit] = db.run(table.filter(_.phone === row.phone).update(row)).
    map(_ => ())

  def selectGetRole(account: String, password: String) = {
    db.run(table.filter(x => x.phone === account)
      .filter(_.password === password).result.headOption.map(op => op.map { x => Role.WechatMember}))
  }

}
